// @ts-ignore
import * as XLSX from 'xlsx/xlsx.mjs'
//文件读取
const readFile = (file:Blob | File)=>{
    return new Promise(resolve => {
        const reader = new FileReader();
        //以二进制的方式读取
        reader.readAsBinaryString(file);
        reader.onload = ev =>{
            resolve(ev.target?.result);
        }
    })
}
/**
 * 读取Excel文件
 * @param ev 事件对象
 * @param callback 回调函数
 * @options 配置项{
 *  sheetIndexs: [0], // 读取的Sheet索引
 *  sheetNames: ['考勤记录'], // 读取的Sheet名称
 *  type: "binary" // 读取的数据类型
 * }
*/
export const readExcel = async(
    file:Blob | File | null | undefined,
    callback:Function,
    options:{ [key:string]:any } = {}
)=>{
    options = {
        type:'binary',
        ...options
    }
    return new Promise(async resolve => {
        if(!file){
            console.log("文件打开失败")
            return
        }else{
            const data = await readFile(file)
            // 解析二进制格式数据
            const workbook = XLSX.read(data,{ type: "binary"})
            // json数据格式
            const json = getSheetJson(workbook,options)
            const result = {
                json,
                workbook
            }
            resolve(result)
            callback(result)
        }
    })
}
// 获取工作表json
function getSheetJson(workbook:any,options:any)
{
    // 有索引针对索引导出
    if(options.sheetIndexs!==undefined){
        return options.sheetIndexs.map((index:any)=>{
            const worksheet = workbook.Sheets[workbook.SheetNames[index]]
            const json = XLSX.utils.sheet_to_json(worksheet,{ header:1,defval:'' })
            return json
        })
    }
    // 针对名称导出,没名称默认全部
    const returnSheetNames = options.sheetNames || workbook.SheetNames
    return returnSheetNames.map((item:any)=>{
        const worksheet = workbook.Sheets[item]
        const json = XLSX.utils.sheet_to_json(worksheet,{ header:1,defval:'' })
        return json
    })
}